// pages/gangManage/productEdit/productEdit.js
const app = getApp()
var util = require('../../../utils/util.js')
var http = require('../../../utils/server.js')

Page({
  data: {
    type: [],
    typeIndex: 0,
    brand: [],
    brandIndex: 0,
    version: ['CH', 'TW', 'SP'],
    versionIndex: 0, //固定三个版本 
    model: '',
    imgs: [],
    classify: 1,
    specifications: [],
    product_id: "",
    afterSaleIsSetting: "",
    passageCount: 0
  },


  onLoad: function(option) {
    var that = this
    // 有ID 查 是官方还是自有商品 没ID 新增自由商品
    // 自有商品可以改所有 官方只能改零售和帮会价格
    that.setData({
      product_id: option.product_id || ""
    })

    http.post({
      url: "product/getFilterData",
      type: ''
    }, function(data) {
      console.log('品牌分类数据', data)
      that.setData({
        type: data[0].data,
        brand: data[1].data
      })
    })

    if (that.data.product_id) {
      wx.setNavigationBarTitle({
        title: '编辑商品'
      })
      http.post({
        url: "product/getDetail",
        product_id: that.data.product_id
      }, function(data) {
        if (data.sold_out == 1) {
          console.log('该商品已经下架')
          util.showError('该商品已经下架')
          setTimeout(function() {
            wx.redirectTo({
              url: "/pages/gangManage/productManage/productManage"
            })
          }, 1500)
        } else {
          console.log('商品规格', data.specifications)
          var type = that.data.type
          var brand = that.data.brand
          var typeIndex = brandIndex = 0
          for (t in type) {
            if (type[t]['id'] == data.type) {
              brandIndex = t
              break;
            }
          }
          for (t in brand) {
            if (brand[t]['id'] == data.brand) {
              brandIndex = t
              break;
            }
          }
          var versionIndex = 0
          versionIndex = data.version ? that.data.version.indexOf(data.version) : 0

          var imgs = [];
          for (p in data.pics) {
            imgs.push({
              src: data.pics[p],
              cover: false
            })
          }
          that.setData({
            specifications: data.specifications,
            classify: data.classify,
            model: data.model,
            brandIndex: brandIndex,
            typeIndex: typeIndex,
            versionIndex: versionIndex,
            imgs: imgs,
            passageCount: data.passage_count,
            afterSaleIsSetting: data.after_sale_is_setting,

          })
        }
      })
    } else {
      wx.setNavigationBarTitle({
        title: '新增商品'
      })
    }
  },

  bindPickerChange: function(e) {
    var that = this
    var index = e.currentTarget.dataset.index;
    if (index == 0) {
      that.setData({
        typeIndex: e.detail.value
      })
    } else if (index == 1) {
      that.setData({
        brandIndex: e.detail.value
      })
    } else if (index == 2) {
      that.setData({
        versionIndex: e.detail.value
      })
    }
  },
  bindModel: function(e) {
    this.setData({
      model: e.detail.value
    })
  },
  addPic: function(e) {
    var that = this
    if (that.data.imgs.length > 9) {
      util.showModal("最多只能上传10张")
      return false;
    }
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success: function(res) {
        var tempFilePaths = res.tempFilePaths
        var imgs = that.data.imgs
        imgs.unshift({
          src: tempFilePaths[0],
          cover: true,
          coverHeight: 100
        })
        that.setData({
          imgs: imgs
        })

        var token = wx.getStorageSync('token') || "";
        const uploadTask = wx.uploadFile({
          url: 'https://www.ymqvip.com/api/upload/uploadPic',
          filePath: tempFilePaths[0],
          name: 'imgfile',
          formData: {
            'token': token
          },
          success: function(res) {
            var uploadData = JSON.parse(res.data)
            if (uploadData.code == 0) {
              console.log('上传成功', uploadData.data)
              var imgs = that.data.imgs
              imgs[0].src = uploadData.data
              imgs[0].cover = false
              that.setData({
                imgs: imgs
              })
            } else {
              util.showModal("上传出错，" + res.message)
              return false;
            }
          },
          fail: function(e) {
            console.log('上传出错', e)
            util.showModal("上传出错，请联系管理员。")
            return false;
          }
        })

        uploadTask.onProgressUpdate((res) => {
          var imgs = that.data.imgs
          imgs[0].coverHeight = 100 - res.progress
          // console.log('上传进度', imgs[0].coverHeight)
          that.setData({
            imgs: imgs
          })
        })

      }
    })

  },
  delPic: function(e) {
    var that = this
    var index = e.currentTarget.dataset.index
    var imgs = that.data.imgs
    imgs.splice(index, 1)
    that.setData({
      imgs: imgs
    })
  },
  bindEditPrice(e) {
    var index = e.currentTarget.dataset.index
    var stype = e.currentTarget.dataset.type
    var specifications = this.data.specifications
    specifications[index][stype] = e.detail.value
    this.setData({
      specifications: specifications
    })
  },
  sub: function(e) {
    var index = e.currentTarget.dataset.index
    var stype = e.currentTarget.dataset.type
    var specifications = this.data.specifications
    if (typeof(specifications[index][stype]) == "undefined")
      specifications[index][stype] = 0
    specifications[index][stype]--
      if (specifications[index][stype] <= 1) {
        specifications[index][stype] = 1
        specifications[index][stype + "_disabled"] = true
      }
    this.setData({
      specifications: specifications
    })
  },
  add: function(e) {
    var index = e.currentTarget.dataset.index
    var stype = e.currentTarget.dataset.type
    var specifications = this.data.specifications
    if (typeof(specifications[index][stype]) == "undefined")
      specifications[index][stype] = 0
    specifications[index][stype]++
      specifications[index][stype + "_disabled"] = false
    this.setData({
      specifications: specifications
    })
  },
  addSpecifications: function(e) {
    var specifications = this.data.specifications
    specifications.push({})
    this.setData({
      specifications: specifications
    })
  },
  delSpecifications: function(e) {
    var that = this
    var index = e.currentTarget.dataset.index
    var specifications = that.data.specifications
    specifications.splice(index, 1)
    that.setData({
      specifications: specifications
    })
  },
  bindSTitle: function(e) {
    var that = this
    var index = e.currentTarget.dataset.index
    var specifications = that.data.specifications
    specifications[index].title = e.detail.value
    that.setData({
      specifications: specifications
    })
  },
  soldOut(e) {
    var that = this;
    wx.showModal({
      title: '操作提示',
      content: '确定下架该商品？(若需再次上架请在“上架商品”中操作)',
      success: function(res) {
        if (res.confirm) {
          //下架
          http.post({
            url: "product/soldOut",
            product_id: that.data.product_id,
          }, function(data) {
            util.showSuccess('下架成功', function() {
              wx.redirectTo({
                url: "/pages/gangManage/productManage/productManage"
              })
            })
          })
        }
      }
    })
  },
  formSubmit: function(e) {
    var that = this
    var pics = [];
    for (p in that.data.imgs) {
      pics.push(that.data.imgs[p].src)
    }
    if (that.data.product_id) {
      http.post({
        url: "product/editProduct",
        product_id: that.data.product_id,
        brand: e.detail.value.brand,
        model: e.detail.value.model,
        type: e.detail.value.type,
        version: e.detail.value.version,
        specifications: that.data.specifications,
        pics: pics
      }, function(data) {
        util.showSuccess('修改成功', function() {
          wx.redirectTo({
            url: "/pages/gangManage/productManage/productManage"
          })
        })

      })
    } else {
      http.post({
        url: "product/createProduct",
        brand: e.detail.value.brand,
        model: e.detail.value.model,
        type: e.detail.value.type,
        version: e.detail.value.version,
        specifications: that.data.specifications,
        pics: pics
      }, function(data) {
        util.showSuccess('新增成功', function() {
          wx.redirectTo({
            url: "/pages/gangManage/productManage/productManage"
          })
        })
      })
    }
  },
  setAfterSale: function(e) {
    this.setData({
      afterSaleIsSetting: e
    })
  },
  setPassageCount: function(e) {
    this.setData({
      passageCount: e
    })
  }
})